import { login, getProfile, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken, setTimeOut } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    delToken(state) {
      state.token = ''
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    logout(context) {
      context.commit('delToken')
      context.commit('delUserInfo')
    },
    // 登录
    async userLogin(context, formDate) {
      const res = await login(formDate)
      console.log(res)
      context.commit('setToken', res.data)
      setTimeOut()
    },
    // 获取用户信息
    async getUserInfo(context) {
      const res = await getProfile()
      console.log(res)
      const info = await getUserInfo(res.data.userId)
      console.log(info)
      context.commit('setUserInfo', { ...res.data, ...info.data })
    }
  }
}
